<?php

namespace {{namespace}};

use app\{{extendClass}};
use {{modelClass}}\{{className}} as {{className}}Model;
use {{validateClass}}\{{className}} as {{className}}Validate;
use think\exception\ValidateException;

class {{className}} extends {{extendClass}}
{
    protected $model;
    protected $validate;

    public function initialize()
    {
        $this->model = new {{className}}Model();
        $this->validate = new {{className}}Validate();
    }

    public function index()
    {
        return $this->model->select();
    }

    public function read($id)
    {
        return $this->model->find($id);
    }

    public function save()
    {
        try {
            $this->validate->sceneCreate()->check(request()->post());
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(['code' => 400, 'msg' => $e->getError()]);
        }

        return $this->model->save(request()->post()) ? json(['code' => 200]) : json(['code' => 500]);
    }

    public function update($id)
    {
        try {
            $this->validate->sceneUpdate()->check(request()->put());
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return json(['code' => 400, 'msg' => $e->getError()]);
        }

        return $this->model->where('id', $id)->update(request()->put()) ? json(['code' => 200]) : json(['code' => 500]);
    }

    public function delete($id)
    {
        return $this->model->destroy($id) ? json(['code' => 200]) : json(['code' => 500]);
    }
}
